package team.archai.nexus.boot.platform.basics.endpoint;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import team.archai.nexus.boot.platform.basics.dto.BasicsDTO;
import team.archai.nexus.boot.platform.basics.entity.BasicsEntity;
import team.archai.nexus.boot.platform.basics.service.BasicsService;
import team.archai.nexus.boot.platform.core.vo.PageResult;
import team.archai.nexus.boot.web.response.RequestModel;
import team.archai.nexus.boot.web.response.ResponseModel;
import team.archai.nexus.boot.web.response.ResultUtil;


import java.util.Optional;

/**
 * @author lishibin
 * @desc: 基础控制类
 * @date 2021-11-18
 */
public abstract class BasicsEndPoint<S extends BasicsService<DTO, T>, DTO extends BasicsDTO, T extends BasicsEntity> {

    @Autowired
    protected S service;


    @GetMapping("/pages")
    @Operation(summary = "通用分页查询", description = "通用分页查询")
    protected ResponseModel<PageResult<T>> pages(@RequestBody(required = false) RequestModel<T> query) {
        query = Optional.ofNullable(query).orElse(new RequestModel<>());
        T t = query.getT();
        Page<T> page = new Page<>(query.getCurrent(), query.getSize());
        IPage<T> result = service.page(page, Wrappers.query(t));
        return ResultUtil.success(new PageResult<T>(result.getTotal(), result.getRecords(), result.getCurrent(), result.getSize()));
    }


    @GetMapping("/{id}")
    @Operation(summary = "通用查询详情", description = "通用查询详情")
    protected ResponseModel<T> find(@PathVariable Long id) {
        return ResultUtil.success(service.getById(id));
    }

    @PostMapping()
    @Operation(summary = "通用保存", description = "通用保存")
    @ApiResponse(responseCode = "200", description = "成功返回true否则false")
    protected ResponseModel<Boolean> save(@RequestBody(required = false) T t) {
        return ResultUtil.success(service.saveOrUpdate(t));
    }


    @PutMapping()
    @ApiResponse(responseCode = "200", description = "成功返回true否则false")
    @Operation(summary = "通用更新", description = "通用更新")
    protected ResponseModel<Boolean> update(T t) {
        return ResultUtil.success(service.updateById(t));
    }


    @DeleteMapping("/{id}")
    @Operation(summary = "通用删除", description = "通用删除")
    @ApiResponse(responseCode = "200", description = "成功返回true否则false")
    protected ResponseModel<Boolean> remove(@PathVariable Long id) {
        return ResultUtil.success(service.removeById(id));
    }

}
